<?php

namespace App\Http\Controllers\Api\Goods;

use DB;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Models\Goods\GoodsMaster;  //商品主表

use App\Models\ConfigureFunction; //设置表

use App\Models\Mall\MallMaster;

use App\Service\PromotionService;

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\WdhService;

use App\Models\Goods\GoodsSale;

use App\Models\Goods\GoodsStore;

use App\Models\Promotion\PromotionGroup;

use App\Models\Promotion\PromotionGroupGoods;

use App\Models\Customer\CustCollection;

use App\Models\Goods\GoodsPicture;

use App\Models\Goods\GoodsSpecRelation;

use App\Models\Goods\GoodsMarktingStrategy;

use App\Models\SysTag;

use App\Models\SysItem;

use App\Models\ConfigureTag;

use App\Models\ConfigureTagRelation;

use App\Models\Goods\GoodsComment;

class GoodsController extends Controller
{

    /**
     * 商品列表初始化
     * @param Request $request
     * @return array
     */
    public function listInit(Request $request)
    {
        $return_data = [
            'hot_search' => ''
        ];

        $hot_search_data = SysItem::select('itemID', 'itemName')->where(['itemCategoryID'=>100])->get();
        if ( $hot_search_data ) {
            $return_data['hot_search'] = $hot_search_data->toArray();
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
    }

    /**
     * 商品分类列表&商品列表页&商品搜索页
     * @param Request $request
     * @return array
     */
    public function search(Request $request)
    {
        //1.商品分类列表  2.商品列表页  3.商品搜索页
        $type = $request->input('type');
        $platform = $request->input('platform', 6);
        $mallID = $request->input('mallID', 0);
        $page = $request->input('page', 1);
        $rp = $request->input('rp', 5);
        $sortname = $request->input('sortname', 'timeStamp');
        $sortorder = $request->input('sortorder', 'desc');
        $brandID = $request->input('brandID');
        $keyword = $request->input('keyword');
        $bigCategoryID = $request->input('bigCategoryID', 0);
        $midCategoryID = $request->input('midCategoryID', 0);
        $smallCategoryID = $request->input('smallCategoryID', 0);
        $session_id = $request->input('session_id', session_id());
        $shop_id = 1;
        $mall_area_id = 0; //门店区域id

        if (!ebsig_is_int($type)) {
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }

        if (empty($session_id)) {
            return response()->json(['code' => 100002, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);

        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');

        if ($is_open_choose_mall == 1) {

            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 100003, 'message' => '请先选择门店']);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100004, 'message' => '门店不存在']);
            }
            $shop_id = $mallID;
            $mall_area_id = $mall['mallareaID'];

        }

        if (!empty($sortname)) {
            switch ($sortname) {
                case 'price':
                    $sortname = 'salePrice';
                    break;
                case 'update':
                    $sortname = 'timeStamp';
                    break;
                case 'discount':
                    $sortname = 'discount';
                    break;
                case 'sale':
                    $sortname = 'saletotal';
                    break;
                default:
                    $sortname = 'timeStamp';
                    break;
            }
        }

        $brand = '';
        if ($type == 2 && !empty($brandID)) {
            $brand_data = explode(',', $brandID);
            if (isset($brand_data[1])) {
                $brand = $brand_data;
                $brandID = 0;
            }
        }

        //查询参数
        $args_data = [
            'brandID' => $brandID,
            'brand' => $brand,
            'keyword' => $keyword,
            'bigCategoryID' => $bigCategoryID,
            'midCategoryID' => $midCategoryID,
            'smallCategoryID' => $smallCategoryID,
            'page' => $page,
            'rp' => $rp,
            'sortname' => $sortname,
            'sortorder' => $sortorder,
            'shop_id' => $shop_id
        ];

        if ($type == 3) {
            $goods_data = GoodsMaster::getListByKeyword($args_data);
        } else {
            $goods_data = GoodsMaster::getList($args_data);
        }

        if (empty($goods_data['data'])) {
            return response()->json(['code' => 100005, 'message' => '暂无商品']);
        }

        $return_goods_data = array();

        foreach ($goods_data['data'] as &$goods) {

            if ($goods['salePrice'] <= 0) {
                $goods_data['data']['count'] -= 1;
                continue;
            }

            $tag_data = array();

            //商品促销查询
            $promotion_data = PromotionService::goods(array(
                'postID' => $goods['postID'],
                'salePrice' => $goods['salePrice'],
                'salePoints' => isset($goods['salePoints']) ? $goods['salePoints'] : 0,
                'product_code' => $goods['product_code'],
                'marketPrice' => $goods['marketPrice'],
                'goods_amount' => 1,
                'pcustID' => $pcustID,
                'mallareaID' => $mall_area_id,
                'mallID' => $mallID,
                'platform' => 0
            ));
            if (!isset($promotion_data['promotion']) && empty($promotion_data['promotion'])) {
                $price = $goods['salePrice'];
            } else {
                $price = $promotion_data['price'];
                foreach ($promotion_data['promotion'] as $p) {
                    if (isset($p['selected']) && $p['selected'] == 1) {
                        $res_data = SysTag::getCache($p['promotion_type']); //查询商品标签信息
                        if ($res_data) {
                            $tag_data[] = $res_data;
                        }
                    }
                }
            }

            //查询商品标签
            $tag_relation_data = ConfigureTagRelation::where(['relation_id'=>$goods['mainPostID'],'relation_type'=>1])->get()->toArray();
            if ($tag_relation_data) {
                foreach ($tag_relation_data as $tag) {
                    $reslut_data = ConfigureTag::where(['tag_id'=>$tag['tag_id']])->first();
                    if ($reslut_data) {
                        $reslut_data = $reslut_data->toArray();
                        $tag_data[] = $reslut_data;
                    }
                }
            }

            $return_goods_data[] = array(
                'mainPostID' => $goods['mainPostID'],
                'postID' => $goods['postID'],
                'goodsName' => $goods['goodsName'],
                'salePrice' => round($goods['salePrice'], 2),
                'marketPrice' => round($goods['marketPrice'], 2),
                'wap_link' => $goods['wap_link'],
                'img_link' => $goods['img_link'],
                'price' => round($price, 2),
                'enableSaleAmount' => $goods['enableSaleAmount'],
                'tag' => $tag_data,
                'spec_num' => isset($goods['spec_num']) ? $goods['spec_num'] : 0
            );

        }

        //查询购物车按钮
        $cart_btn = '';
        $cart_btn_setting_data = ConfigureFunction::getConfigure(14);
        if ( $cart_btn_setting_data ) {
            if ( $type == 1 ) {
                if (isset($cart_btn_setting_data['category']) && $cart_btn_setting_data['category']['is_show'] == 1) {
                    $cart_btn = $cart_btn_setting_data['category']['cart_image'];
                }
            } else if ( $type == 2 ) {
                if (isset($cart_btn_setting_data['list']) && $cart_btn_setting_data['list']['is_show'] == 1) {
                    $cart_btn = $cart_btn_setting_data['list']['cart_image'];
                }
            } else if ( $type == 3 ) {
                if (isset($cart_btn_setting_data['search']) && $cart_btn_setting_data['search']['is_show'] == 1) {
                    $cart_btn = $cart_btn_setting_data['search']['cart_image'];
                }
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['count' => $goods_data['count'], 'cart_btn' => $cart_btn, 'list' => $return_goods_data]]);

    }

    /**
     * 商品详情
     * @param Request $request
     * @return array
     */
    public function goodsInit(Request $request)
    {
        $session_id = $request->input('session_id', session_id());
        $postID = $request->input('id');
        $platform = $request->input('platform', 6);
        $mallID = $request->input('mallID', 1);
        $host = $request->getSchemeAndHttpHost();

        $pcustID = 0;
        if ($session_id) {
            $pcustID = get_customer_id($session_id, $platform);
        }

        //查询商品信息
        $sale = GoodsSale::getCache($postID);
        if (!$sale) {
            return response()->json(['code' => 100000, 'message' => '商品不存在']);
        }

        if ($sale['forsale'] != 1) {
            return response()->json(['code' => 100000, 'message' => '该商品已下架']);
        }

        $mainPostID = $sale['mainPostID'];

        //查询商品主表信息
        $master = GoodsMaster::find($mainPostID);
        if (!$master) {
            return response()->json(['code' => 100000, 'message' => '商品不存在']);
        }

        $goods_data = [];

        $detail = [
            'mainPostID' => $mainPostID,
            'postID' => $postID,
            'product_code' => $sale['product_code'],
            'goodsName' => $sale['goodsName'],
            'goodsType' => $sale['goodsType'],
            'forsale' => $sale['forsale'],
            'useFlg' => $sale['useFlg'],
            'brandName' => $master['brandName'],
            'unitName' => $master['unitName'],
            'bigCategoryID' => $master['bigCategoryID'],
            'bigCategoryName' => $master['bigCategoryName'],
            'midCategoryID' => $master['midCategoryID'],
            'midCategoryName' => $master['midCategoryName'],
            'smallCategoryID' => $master['smallCategoryID'],
            'smallCategoryName' => $master['smallCategoryName'],
            'goodsMainPic' => $master['goodsMainPic'],
            'brief' => $master['brief'],
            'memo' => $master['memo'],
            'marketPrice' => $sale['marketPrice'],
            'salePrice' => $sale['salePrice'],
            'saletotal' => $master['saletotal'],
            'description' => !empty($master['mobile_description']) ? $master['mobile_description'] : $master['pc_description'],
            'goods_limit' => $master['goods_limit'],
            'virtual_total' => $master['virtual_total'],
        ];

        $goods_data['img_link'] = $host . $master['goodsMainPic']; //商品主图
        $goods_data['share_img_url'] = $host . $master['goodsMainPic']; //微信分享图片
        $goods_data['salesVolume'] = -1; //商品销量
        $goods_data['enable_sale_amount'] = -1; //无库存
        //查询商品设置信息
        $configure_data = ConfigureFunction::getConfigure(30);
        if ($configure_data) {
            if ($configure_data['is_saletotal_type'] == 1) {   //商品销量
                $goods_data['salesVolume'] = $detail['saletotal'] + $detail['virtual_total'];
            }

            if ($configure_data['is_stock_type'] == 1) {
                $goods_data['enable_sale_amount'] = GoodsStore::search($sale['product_code'], $sale['product_spec'], $mallID);
            }
        }

        $goods_data['detail'] = $detail;

        //查询商品图片信息
        $pic = GoodsPicture::where(['mainPostID' => $mainPostID])->get()->toArray();
        if ($pic) {
            foreach ($pic as &$p) {
                if (empty($p['pictureLink'])) {
                    continue;
                }
                $goods_data['pic'][] = $host . $p['pictureLink'];
            }
        }

        //查询会员收藏信息
        $goods_data['collect'] = 0;
        $collect = CustCollection::where(['pcustID' => $pcustID, 'postID' => $postID])->first();
        if ($collect) {
            $goods_data['collect'] = 1;
        }

        /**
         * 检查商品套装或者组合
         */
        $goods_data['is_package'] = 0; //is_package：0.无套装  1.有套装
        $goods_data['is_group'] = 0; //is_group：0.无组合  1.有组合
        $goods_group = PromotionGroupGoods::where(['postID' => $postID, 'goodsType' => 1])->get()->toArray();
        if ($goods_group) {
            foreach ($goods_group as $goods) {
                $group_data = PromotionGroup::where(['promotion_id' => $goods['promotion_id'], 'useFlg' => 1])->first();
                if ($group_data) {
                    $group_data = $group_data->toArray();

                    if ($group_data['start_time'] != '0000-00-00 00:00:00' && $group_data['end_time'] != '0000-00-00 00:00:00') {
                        if ($group_data['start_time'] > Carbon::now() || $group_data['end_time'] < Carbon::now()) {
                            continue;
                        }
                    }

                    if ($group_data['group_type'] == 1) {
                        $goods_data['is_package'] = 1;
                    }

                    if ($group_data['group_type'] == 2) {
                        $goods_data['is_group'] = 1;
                    }
                }

            }
        }

        //查询评论统计数量
        $goods_data['comment_stat'] = GoodsComment::getCommentCount( $mainPostID, $pcustID );

        /**
         * =============start猜你喜欢======================
         */
        $args_data = array(
            'shop_id' => 1,
            'mallID' => 0,
            'mall_area_id' => 0,
            'bigCategoryID' => $master['bigCategoryID'],
            'midCategoryID' => $master['midCategoryID']
        );
        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');
        if ($is_choose_goods_by_mall) {
            $args_data['shop_id'] = $mallID;
            $args_data['mallID'] = $mallID;
        }
        $goods_data['may_like'] = GoodsMaster::getRandGoods($args_data, $pcustID, 6);;
        if ($goods_data['may_like']) {
            foreach ($goods_data['may_like'] as &$may) {
                $may['img_link'] = $host . $may['img_link'];
            }
        }

        /**
         * =============end猜你喜欢======================
         */

        //查询购物车按钮
        $goods_data['is_show_buy_btn'] = 1;
        $buy_btn_setting_data = ConfigureFunction::getConfigure(14);
        if (isset($buy_btn_setting_data['buy_btn']) && $buy_btn_setting_data['buy_btn']['is_show'] == 0) {
            $goods_data['is_show_buy_btn'] = 0;
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $goods_data]);

    }

    /**
     * 获取商品规格&促销
     * @param Request $request
     * @return array
     */
    public function detail(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $mainPostID = $request->input('mid');
        $group_type = $request->input('group_type');//套装标识
        $groupID = $request->input('groupID');
        $platform = $request->input('platform', 6);
        $mallID = $request->input('mallID', 1);
        $host = $request->getSchemeAndHttpHost();

        $pcustID = 0;
        if ($session_id) {
            $pcustID = get_customer_id($session_id, $platform);
        }

        if (!ebsig_is_int($mainPostID)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：mid']);
        }

        if (!ebsig_is_int($group_type)) {
            $group_type = 0;
        }

        if (!ebsig_is_int($groupID)) {
            $groupID = 0;
        }

        $mall_area_id = 0;
        if (ebsig_is_int($mallID)) {
            $mall = MallMaster::find($mallID);
            if ($mall) {
                $mall_area_id = $mall['mallareaID'];
            }

        }

        //查询主商品信息
        $master = GoodsMaster::find($mainPostID);
        if (!$master) {
            return response()->json(['code' => 10001, 'message' => '商品不存在']);
        }

        //查询商品规格信息
        $goods_spec = GoodsSpecRelation::getList($mainPostID);

        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall');

        //获取不同规格组合的商品信息
        $goods_list = [];
        $goods_sale_list = GoodsSale::where(['mainPostID' => $mainPostID])->get()->toArray();
        if (!$goods_sale_list) {
            return response()->json(['code' => 10002, 'message' => '商品不存在']);
        }
        foreach ($goods_sale_list as &$g) {

            $g['promotion'] = [];
            $g['order_promotion'] = [];
            $g['price'] = $g['salePrice'];

            //检查库存及门店销售价格
            if ($is_choose_goods_by_mall) {

                $enable_sale_amount = GoodsStore::search($g['product_code'], $g['product_spec'], $mallID);

                //门店销售策略表
                $goods_marketing_strategy = GoodsMarktingStrategy::where(['shop_id' => $mallID, 'postID' => $g['postID']])->first();
                if ($goods_marketing_strategy) {
                    $goods_marketing_strategy = $goods_marketing_strategy->toArray();
                    $g['marketPrice'] = $goods_marketing_strategy['marketPrice'];
                    $g['salePrice'] = $goods_marketing_strategy['salePrice'];
                    $g['salePoints'] = $goods_marketing_strategy['salePoints'];
                    $g['price'] = round($goods_marketing_strategy['salePrice'], 2);
                }

            } else {
                $enable_sale_amount = GoodsStore::search($g['product_code'], $g['product_spec']);
            }

            //查询促销信息
            $goods_promotion = PromotionService::goods([
                'postID' => $g['postID'],
                'salePrice' => $g['salePrice'],
                'salePoints' => $g['salePoints'],
                'product_code' => $g['product_code'],
                'marketPrice' => $g['marketPrice'],
                'goods_amount' => 1,
                'pcustID' => $pcustID,
                'mallareaID' => $mall_area_id,
                'mallID' => $mallID,
                'platform' => 0
            ]);

            if (isset($goods_promotion['promotion']) && !empty($goods_promotion['promotion'])) {
                $g['price'] = $goods_promotion['price'];
                foreach ($goods_promotion['promotion'] as $p) {
                    if (isset($p['selected']) && $p['selected'] == 1) {
                        $g['promotion'][] = $p;
                    }
                }
            }

            /**
             * 检查订单促销
             */
            $promotion_order_data = PromotionService::orders(array(
                'pcustID' => $pcustID,
                'mallareaID' => $mall_area_id,
                'mallID' => $mallID,
                'is_use_coupon' => 2,
                'platform' => 0,
            ), array(
                array(
                    'postID' => $g['postID'],
                    'goods_amount' => 1
                )
            ));

            if (!empty($promotion_order_data)) {
                $g['order_promotion'] = $promotion_order_data;
            }

            //套装商品价格
            $g['unitPrice'] = 0;
            $g['discountPrice'] = 0;
            if ($group_type == 1) {
                $group_data = PromotionGroupGoods::where(['promotion_id' => $groupID, 'postID' => $g['postID']])->first();
                if ($group_data) {
                    $group_data = $group_data->toArray();
                    $g['unitPrice'] = $group_data['unitPrice']; //套装组合单价
                    $g['discountPrice'] = $group_data['discountPrice']; // 套装优惠价格
                }
            }

            $temp_goods_spec_id = explode(',', $g['specID']);
            $spec_key = '';
            foreach ($temp_goods_spec_id as &$id) {
                if (!empty($id)) {
                    $spec_key .= $id;
                }
            }
            if (empty($spec_key)) {
                $spec_key = 0;
            }

            $goods_list[$spec_key] = [
                'id' => $g['postID'],
                'forsale' => $g['forsale'],
                'marketPrice' => $g['marketPrice'],
                'salePrice' => $g['salePrice'],
                'salePoints' => $g['salePoints'],
                'price' => $g['price'],
                'enable_sale_amount' => $enable_sale_amount,
                'spec' => $g['spec'],
                'img_link' => $host . $g['goodsMainPic'],
                'promotion' => $g['promotion'],
                'order_promotion' => $g['order_promotion'],
                'unitPrice' => $g['unitPrice'],
                'discountPrice' => $g['discountPrice'],
                'virtual_id' => $g['virtual_id']
            ];

        }

        //查询购物车按钮
        $is_show_buy_btn = 1;
        $buy_btn_setting_data = ConfigureFunction::getConfigure(14);
        if (isset($buy_btn_setting_data['buy_btn']) && $buy_btn_setting_data['buy_btn']['is_show'] == 0) {
            $is_show_buy_btn = 0;
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => [
            'is_show_buy_btn' => $is_show_buy_btn,
            'goodsType' => $master['goodsType'],
            'spec' => $goods_spec,
            'list' => $goods_list
        ]]);

    }

}
